package com.atguigu.admin.controller;


import com.atguigu.admin.model.menu.MinIOEnum;
import com.atguigu.common.result.Result;
import com.atguigu.core.config.MinioConfig;
import com.atguigu.core.config.MinioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.minio.messages.Bucket;

import java.util.List;

/**
 * @author 90632
 */
@Api(tags = "文件管理")
@RestController
@RequestMapping("/admin/file")
@CrossOrigin
public class FileController {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioConfig prop;

    @Value("${minioTemp.endpoint}")
    private String endpoint;

    @Value("${minioTemp.bucketName}")
    private String bucketName;

    @ApiOperation(value = "查看存储桶是否存在")
    @GetMapping("/bucketExists")
    public Result bucketExists(@RequestParam("bucketName") String bucketName) {
        return Result.ok(minioUtil.bucketExists(bucketName));
    }


    @ApiOperation(value = "文件上传返回url")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        //具体文件，存储桶名称，存储路径
        String objectName = minioUtil.upload(file, MinIOEnum.USER_BUCKET.getName(), MinIOEnum.USER_BUCKET_IMAGES.getName());
        if (null != objectName) {
            return Result.ok(endpoint + "/" + bucketName + "/" + objectName);
        }
        return Result.fail("文件上传错误");
    }

    @ApiOperation(value = "删除存储bucket")
    @GetMapping("/removeBucket")
    public Result removeBucket(String bucketName) {
        return Result.ok(minioUtil.removeBucket(bucketName));
    }

    @ApiOperation(value = "获取全部bucket")
    @GetMapping("/getAllBuckets")
    public Result getAllBuckets() {
        List<Bucket> allBuckets = minioUtil.getAllBuckets();
        return Result.ok(allBuckets);
    }
}
